﻿using System.Numerics;
using NodeCanvas.Framework;
using ParadoxNotion.Design;
using UnityEngine;
using Quaternion = UnityEngine.Quaternion;
using Vector3 = UnityEngine.Vector3;

namespace Yoozoo.Gameplay.Liberty.AI.Node
{
    [Category("Ggame/Liberty")]
    public class NpcBeBarged : AIBaseNode
    {

        public BBParameter<float> rotateSpeed = 1f;

        private Quaternion targetToRot;
        private Transform parent;
            
        protected override void OnExecute()
        {
            parent = _entity.seeker.LocomotionAgent.transform.parent;
            
            var player = LibertyAIUtils.PlayerController.playerModel;
            UnityEngine.Vector3 v1 = UnityEngine.Vector3.Cross(player.forward, UnityEngine.Vector3.up);
            UnityEngine.Vector3 v2 = UnityEngine.Vector3.Cross(player.forward, UnityEngine.Vector3.down);


            float d1 = UnityEngine.Vector3.Distance(-v1.normalized + _entity.data.position, player.position);
            float d2 = UnityEngine.Vector3.Distance(-v2.normalized + _entity.data.position, player.position);
            
            if (d1 > d2)
            {
                targetToRot = Quaternion.LookRotation(v1);
            }
            else
            {
                targetToRot = Quaternion.LookRotation(v2);
            }
            
            // if (Vector3.Angle(v1,_entity.data.forward) > Vector3.Angle(v2,_entity.data.forward))
            // {
            //     targetToRot = Quaternion.LookRotation(v2);
            // }
            // else
            // {
            //     targetToRot = Quaternion.LookRotation(v1);
            // }
        }


        protected override void OnUpdate()
        {
            parent.rotation =
                Quaternion.Slerp(_entity.data.rotation, targetToRot, Time.fixedDeltaTime * rotateSpeed.value);

            _entity.seeker.transform.rotation = parent.rotation;
            
            base.SetTransformData();
            _entity.seeker.SetForceUpdateTargetRotation(parent.rotation);
            if (Quaternion.Angle(parent.rotation,targetToRot) < 0.05f)
            {
                EndAction();
            }
        }
    }
}